<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\CarDealer;

use AuctionCore\AuctionOrder\AuOrderList;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\CouponList;
use AuctionCore\Other\Address;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\CarResource\Car;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Other\Raffle;
use AuctionCore\AuctionOrder\AuOrder;

/**
 * "买到的车"列表
 * @author       爱民
 */
class BuyCarList extends AuOrderList
{

    private $dealer_id = null;

    private $base_sql = null;
    private $count_sql = null;

    public function __construct($dealer_id)
    {
        $this->dealer_id = $dealer_id;

        $query_sql = "SELECT c.model_id,c.car_color,c.plate_prefix,c.plate_suffix,t.* ";
        $sql = " FROM (
               SELECT a.man_id,a.take_method,b.order_id,b.order_no,b.car_id,b.coupon,b.dealer_confirm_status
                   ,b.status,b.trade_time,b.bid_best_price,b.bidding_best_price
                   ,b.success_price,b.commision,b.transfer_fee,b.deliver_type,b.pay_type
                   FROM au_dealer_auctioned a LEFT JOIN au_order b 
                   ON a.order_id = b.order_id 
             WHERE a.status=0 AND a.dealer_id={$dealer_id}
             ) t LEFT JOIN au_cars c
            ON t.car_id = c.car_id";
        $this->base_sql = $query_sql . $sql;
        $this->count_sql = "select count(*) count " . $sql;
    }


    /**
     * 获取列表结果
     * @param    int $ev_page_num 每页条数
     * @param    int $page 页码
     * @return   Object
     */
    public function get($ev_page_num, $page)
    {

        $dealer_id = $this->dealer_id;
        $Model = new \Think\Model();

        //拍单列表信息
        $sql = $this->base_sql;
        $sql .= " {$this->condition}";
        $skip = ($page < 2 ? 0 : $ev_page_num * ($page - 1));
        $sql .= " limit {$skip},{$ev_page_num}";
        $sql .= ";";
        //echo $sql;exit;
        $list = $Model->query($sql);

        $cm = new CarModel();
        foreach ($list as $key => $row) {
            //车型信息
            $list[$key]['model_info'] = $cm->get_parent_brand_info($row['model_id']);

            //过户信息
            $list[$key]['task_man_info'] = $Model->query(
                "SELECT e.real_name,t.*
             FROM (
                SELECT emp_id,company,phone,contact,idcard 
                FROM au_transfer_log 
                WHERE order_id = '{$row['order_id']}'
             ) t LEFT JOIN au_employee e 
            ON t.emp_id = e.emp_id LIMIT 1;");
        }
        return $list;
    }

    /**
     * 获取各状态下拍品数量
     * @param array $params
     * @return int count
     * @author angl
     */
    public function getCount($params)
    {
        return $this->getList(1,10,$params,true);
    }

    /**
     * 获取列表
     * @param $page 当前页码
     * @param $size 每页显示条数
     * @param array $params 参数
     * @param boolen $count_only 是否仅返回统计
     * @return array
     */
    public function getList($page, $size, $params = array(),$count_only=false)
    {
        $page = (int)$page < 2 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;

        //搜索条件
        $map = array();
        $map['o.success_dealer_id'] = array('eq', $this->dealer_id);
        $map['o.is_other_channel_deal'] = array('eq',0); //非其他渠道成交的车辆
        //$map['da.status'] = array('eq', 0);
        //
        $map['_string'] = "o.dealer_issue_status<> 1  AND (o.check_car_status<4)";
        //全部
        if ($params['status'] ==0) {
            # code...
        }
        //成交待确认
        if ($params['status'] ==1) {
            $map['o.status'] = array('neq',12);
            $map['_string'] = "(c.car_source=1 AND (o.status =5 OR o.dealer_pay_status IN(0,1,2) AND o.return_check_status =0 AND o.check_car_status =0) OR (c.car_source=2 AND o.status in(5,7) AND o.dealer_pay_status IN(0,1,2)) AND o.check_car_status =0)";
            $map['_string'] .= " AND o.dealer_issue_status<> 1  AND (o.check_car_status<4 OR (o.check_car_status=5 AND o.status=12))";//不查询争议单，违约未失败的单子属于争议单不展示,只查出违约失败的单子
        }
        //成交待回车 回车复检
        if ($params['status'] == 2) {
            $map['o.return_check_status']  = array('in',array(1,2,3,4));
            $map['c.car_source'] = array('eq',1);//暂只支持4S店的车回车
            $map['o.status'] = array('neq',12);
        }
        //待验车
        if ($params['status'] == 3) {
            $map['o.check_car_status'] = array('in', array(1,2));
            $map['o.status'] = array('neq',12);
            $map['o.dealer_pay_status'] = array('gt',1);
        }
        //待付款
        if ($params['status'] == 4) {
            // $map['o.status'] = array('neq',12);
            // $map['o.dealer_pay_status'] = array('in',array(1,2));
            $map['_string'] = "o.dealer_pay_status IN (1,2)";
            $map['_string'] .= "OR (o.dealer_pay_status = 0 and o.status = 8 and o.return_check_status >4 and c.car_source = 1 )";
            $map['_string'] .= "OR (o.status = 8 and o.dealer_pay_status = 0 and c.car_source = 2 )";

            // in_array($param['dealer_pay_status'],array(1,2)) || ($param['dealer_pay_status'] == 0 && $param['status'] == 8 && $param['check_car_status'] == 3 )
            // in_array($param['dealer_pay_status'],array(1,2)) || ($param['dealer_pay_status'] == 0 && $param['status'] == 8 )
            // in_array($param['dealer_pay_status'],array(1,2)) || (in_array($param['return_check_status'], array(5,7)) && $param['dealer_pay_status'] == 0 && $param['status'] == 8)
            // in_array($param['dealer_pay_status'],array(1,2)) ||  ($param['status']==8 && $param['first_pay_status']==0  && $param['dealer_pay_status']<3)
        }
        //待过户
        if ($params['status'] == 5) {
            $map['_string'] = "(o.status in(9,10) OR (o.check_car_status=3 AND o.dealer_pay_status=3 AND o.`status` =8 AND c.pay_status =1))";//正常单、车商已付款、未付车主首款
            $map['_string'] .= " AND o.dealer_issue_status<> 1  AND (o.check_car_status<4 OR (o.check_car_status=5 AND o.status=12))";//不查询争议单，违约未失败的单子属于争议单不展示,只查出违约失败的单子
        }
        //交易成功
        if ($params['status'] == 6) {
            $map['_string'] = "(o.status =13 OR (o.status = 11 AND tl.result = 2))";
            $map['_string'] .= " AND o.dealer_issue_status<> 1  AND (o.check_car_status<4 OR (o.check_car_status=5 AND o.status=12))";//不查询争议单，违约未失败的单子属于争议单不展示,只查出违约失败的单子
        }
        //交易失败
        if ($params['status'] == 7) {
            //unset($map['da.status']);
            $map['_string'] = "o.status = 12";
            $map['_string'] .= " AND o.dealer_issue_status<> 1  AND (o.check_car_status<4 OR (o.check_car_status=5 AND o.status=12))";//不查询争议单，违约未失败的单子属于争议单不展示,只查出违约失败的单子
        }

        if ($params['brand_id'] > 0) {
            $map['c.brand_id'] = array('eq', $params['brand_id']);
        }

        if ($params['c.series_id'] > 0) {
            $map['c.series_id'] = array("eq", $params['series_id']);
        }
        //成交时间
        if (!empty($params['trade_time'])) {
            $map['o.trade_time'] = array("between", $params['trade_time'] . " 00:00:00", $params['trade_time'] . " 23:59:59");
        }
        //交付方式
        if ($params['deliver_type'] > 0) {
            $map['o.deliver_type'] = array('eq', $params['deliver_type']);
        }
        //支付方式
        if ($params['pay_type'] > 0) {
            $map['o.pay_type'] = array('eq', $params['pay_type']);
        }
        //da.man_id,da.dealer_id,da.take_method,da.order_id,da.status da_status,da.trade_price,
        $cols = "o.trade_time,o.success_price,
            o.order_id,o.order_no,o.status,o.car_id,o.coupon,o.dealer_confirm_status,o.dealer_pay_status,o.bid_best_price,
            o.bidding_best_price,o.commision,o.transfer_fee,o.deliver_type,o.pay_type,o.bidding_end_time,o.compensation,
            c.car_source,o.return_check_status,o.check_car_status,o.transfer_type,
            c.car_id,c.car_no,c.mbrand_id,brand_id,series_id,model_id,c.car_color,c.plate_suffix,c.plate_prefix,c.car_cc,
            c.turbo,c.gearbox,c.transfer_limit,c.location_area,o.scene_id";

        $order_by = "o.bidding_end_time desc,o.order_id desc";

        $prefix = C("DB_PREFIX");

        /*$total = M('dealer_auctioned')->alias("da")
            ->join("{$prefix}order as o ON da.order_id=o.order_id")
            ->join("{$prefix}cars as c  ON o.car_id=c.car_id")
            ->join("LEFT JOIN {$prefix}transfer_log as tl ON tl.order_id = o.order_id")
            ->where($map)->count("distinct(o.order_id)");*/
        $total = M('order')->alias("o")
            ->join("{$prefix}cars as c  ON o.car_id=c.car_id")
            ->join("LEFT JOIN {$prefix}transfer_log as tl ON tl.order_id = o.order_id")
            ->where($map)->count("distinct(o.order_id)");
        if($count_only)return $total;
        /*$list = M('dealer_auctioned')->alias("da")->field($cols)
            ->join("{$prefix}order as o ON da.order_id=o.order_id")
            ->join("{$prefix}cars as c  ON o.car_id=c.car_id")
            ->join("LEFT JOIN {$prefix}transfer_log as tl ON tl.order_id = o.order_id")
            ->where($map)->group("o.`order_id`")->order($order_by)->limit($size)->page($page)->select();*/
        $list = M('order')->alias("o")->field($cols)
            ->join("{$prefix}cars as c  ON o.car_id=c.car_id")
            ->join("LEFT JOIN {$prefix}transfer_log as tl ON tl.order_id = o.order_id")
            ->where($map)->group("o.`order_id`")->order($order_by)->limit($size)->page($page)->select();

        // echo M()->getLastSql();
        // die();
        if (!empty($list)) {
            $cm = new CarModel();
            $Coupon = new CouponList();
            $Raffle = new Raffle();
            $a = new Address();
            foreach ($list as $key => $val) {
                $raffle_price = '';
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $city_name = $a->get_name_by_code($val['location_area']);
                $list[$key]['model'] = '['.$city_name.'] '.$series['name'] . ' ' . $val['car_cc'] . ($val['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $val['gearbox']);


                $coupon_money = $Coupon->getSumCouponCost($this->dealer_id, $val['order_id']);
                if ($coupon_money) {
                    $list[$key]['coupon_money'] = ($val['coupon'] <= 0) ? '0' : ($coupon_money > $val['coupon'] ? $val['coupon'] : $coupon_money);
                }
                //抽奖
                $Raffle_money = $Raffle->find_card_activity($val['order_id'],1);
                if ($Raffle_money && $Raffle_money['state'] >0) {
                    $list[$key]['raffle_money'] = $Raffle_money['price'];
                    $list[$key]['raffle_state'] = $Raffle_money['state'];
                    $raffle_price = $Raffle_money['price'];
                } 
                //车商自行过户 没有过户费
                if ($val['transfer_type'] == 1) {
                    $list[$key]['transfer_fee'] = 0;
                }
                //应付总额
                $val['success_price'] = $val['bidding_best_price']>$val['bid_best_price'] ? $val['bidding_best_price'] : $val['bid_best_price'];
                //场次活动
                $res_activity = $this->is_scene_activity($val['scene_id']);
                if(!empty($res_activity)){
                    //根据场次活动减免规则id找到减免规则
                    foreach($res_activity as $k => $v){
                        if($v['rules_type'] == 2){ //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                            $scene_activity_amount = $this->get_activity_rules_price($v['scene_activity_id'],$val['success_price']);
                        }else if($v['rules_type'] == 1){ //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                            $scene_activity_amount = $v['amount'];
                        }
                    }
                }else{
                    $scene_activity_amount = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
                }
                $list[$key]['total_money'] = $val['success_price'] + $val['commision'] + $list[$key]['transfer_fee'] - $list[$key]['coupon_money'] - $raffle_price - $scene_activity_amount;
                if($val['compensation'] > 0){
                    $list[$key]['total_money'] = $list[$key]['total_money'] - $val['compensation'];
                }
                // $where = [];
                // $where['order_id'] = $val['order_id'];
                // $where['status'] = [['eq',1],['eq',2],'or'];
                // $compensation =  M("dealer_compensate")->where($where)->sum('compensate_amount');
                // $list[$key]['total_money'] = $list[$key]['total_money'] - $compensation;
                // echo $val['trade_price'] ."+". $val['commision'] ."+".  $val['transfer_fee'] ."-". $list[$key]['coupon_money'] ."-". $raffle_price ."-". $val['compensation'];
                $list[$key]['status_name'] = self::get_status($val);
                $list[$key]['status_type'] = self::get_status_type($val);
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 买到的车--车商应看到的车辆处理状态
     * @param array
     * @return array
     */
    public static  function get_status($param=array()){
            //
            $status_cn = '&nbsp;';
            if($param['status']==12){//第一名车商违约，该车商看到的状态应该是交易失败
                $status_cn = '交易失败';
            }elseif($param['status']==11 || $param['status']==13){//待付尾款，拍单成功
                $status_cn = '交易成功';
            }else{
                if($param['car_source']==1){//4S店
                    if(($param['status'] == 5 || ($param['status']==8 && $param['first_pay_status']==0)) && $param['return_check_status'] ==0 ) {
                        $status_cn = '待确认';
                    }elseif(in_array($param['return_check_status'],array(1,2,3,4))){
                        $status_cn = '待回车';
                    }elseif(in_array($param['dealer_pay_status'],array(1,2)) || (in_array($param['return_check_status'], array(5,6,7)) && $param['dealer_pay_status'] == 0 && $param['status'] == 8) ){
                        $status_cn = '待付款';
                    }elseif(in_array($param['check_car_status'],array(1,2))){
                        $status_cn = '待验车';
                    }elseif(in_array($param['status'],array(9,10)) || ($param['check_car_status']==3 && $param['dealer_pay_status']==3 && $param['status']==8 && $param['first_pay_status'] ==0)){
                        $status_cn = '待过户';
                    }
                }elseif($param['car_source']==2){//个人
                    if(in_array($param['status'],array(5,7)) || in_array($param['return_check_status'],array(3,4))){
                        $status_cn = '待确认';
                    }elseif(($param['status']==8 && $param['dealer_pay_status'] ==0 )|| in_array($param['dealer_pay_status'],array(1,2))){
                        $status_cn = '待付款';
                    }elseif(in_array($param['check_car_status'],array(1,2))){
                        $status_cn = '待验车';
                    }elseif(in_array($param['status'],array(9,10)) || ($param['check_car_status']==3 && $param['dealer_pay_status']==3 && $param['status'] ==8 && $param['first_pay_status']==0)){
                        $status_cn = '待过户';
                    }
                }
            }
            return $status_cn;
    }
    /**
     * 买到的车--车商应看到的车辆处理状态--数字
     * @param array
     * @return array
     */
    public static  function get_status_type($param=array()){
        //
        $status_cn = '&nbsp;';
        if($param['status']==12){//第一名车商违约，该车商看到的状态应该是交易失败
            $status_cn = '7';
        }elseif($param['status']==11 || $param['status']==13){//待付尾款，拍单成功
            $status_cn = '6';
        }else{
            if($param['car_source']==1){//4S店
                if(($param['status'] == 5 || ($param['status']==8 && $param['first_pay_status']==0)) && $param['return_check_status'] ==0 ) {
                    $status_cn = '1';
                }elseif(in_array($param['return_check_status'],array(1,2,3,4))){
                    $status_cn = '2';
                }elseif(in_array($param['dealer_pay_status'],array(1,2)) || (in_array($param['return_check_status'], array(5,6,7)) && $param['dealer_pay_status'] == 0 && $param['status'] == 8) ){
                    $status_cn = '4';
                }elseif(in_array($param['check_car_status'],array(1,2))){
                    $status_cn = '3';
                }elseif(in_array($param['status'],array(9,10)) || ($param['check_car_status']==3 && $param['dealer_pay_status']==3 && $param['status']==8 && $param['first_pay_status'] ==0)){
                    $status_cn = '5';
                }
            }elseif($param['car_source']==2){//个人
                if(in_array($param['status'],array(5,7)) || in_array($param['return_check_status'],array(3,4))){
                    $status_cn = '1';
                }elseif(($param['status']==8 && $param['dealer_pay_status'] ==0 )|| in_array($param['dealer_pay_status'],array(1,2))){
                    $status_cn = '4';
                }elseif(in_array($param['check_car_status'],array(1,2))){
                    $status_cn = '3';
                }elseif(in_array($param['status'],array(9,10)) || ($param['check_car_status']==3 && $param['dealer_pay_status']==3 && $param['status'] ==8 && $param['first_pay_status']==0)){
                    $status_cn = '5';
                }
            }
        }
        return $status_cn;
    }
    /**
     * 出价的车--车商应看到的车辆处理状态
     * @param array $flag  1为买到车  2为出价的车
     * @return array
     */
    public static  function get_bid_status($param=array()){
            //
            $status_cn = '';
            if ($param['dealer_issue_status'] == 1) {
                $status_cn = '待仲裁';
            }
            if($param['da_status']>0 || $param['status']==12){//第一名车商违约，该车商看到的状态应该是交易失败
                $status_cn = '交易失败';
            }elseif($param['status']==11 || $param['status']==13){//待付尾款，拍单成功
                $status_cn = '交易成功';
            }else{
                if($param['car_source']==1){//4S店
                    if(($param['status'] == 5 || ($param['status']==8 && $param['first_pay_status']==0)) && $param['return_check_status'] ==0 ) {
                        $status_cn = '待确认';
                    }elseif(in_array($param['return_check_status'],array(1,2,3,4))){
                        $status_cn = '待回车';
                    }elseif(in_array($param['dealer_pay_status'],array(1,2)) || (in_array($param['return_check_status'], array(5,6,7)) && $param['dealer_pay_status'] == 0 && $param['status'] == 8)){
                        $status_cn = '待付款';
                    }elseif(in_array($param['check_car_status'],array(1,2))){
                        $status_cn = '待验车';
                    }elseif((in_array($param['status'],array(9,10)) || ($param['check_car_status']==3 && $param['dealer_pay_status']==3 && $param['status']==8 && $param['first_pay_status'] ==0)) && $param['dealer_issue_status'] != 1){
                        $status_cn = '待过户';
                    }elseif ($param['check_car_status'] == 4 || ($param['check_car_status'] == 5 && $param['status'] < 12)) {
                        $status_cn = '待仲裁';
                    }
                }elseif($param['car_source']==2){//个人
                    if(in_array($param['status'],array(5,7)) || in_array($param['return_check_status'],array(3,4))){
                        $status_cn = '待确认';
                    }elseif(($param['status']==8 && $param['dealer_pay_status'] ==0)|| in_array($param['dealer_pay_status'],array(1,2))){
                        $status_cn = '待付款';
                    }elseif(in_array($param['check_car_status'],array(1,2))){
                        $status_cn = '待验车';
                    }elseif((in_array($param['status'],array(9,10)) || ($param['check_car_status']==3 && $param['dealer_pay_status']==3 && $param['status'] ==8 && $param['first_pay_status']==0)) && $param['dealer_issue_status'] != 1){
                        $status_cn = '待过户';
                    }elseif ($param['check_car_status'] == 4 || ($param['check_car_status'] == 5 && $param['status'] < 12)) {
                        $status_cn = '待仲裁';
                    }
                }

            }
            return $status_cn;
    }


    //出价的车--是否竞得状态
    public function is_get_status($param=array()){
        $map = array();
        $is_get_status = "";
        $map['dealer_id'] = array('eq',$this->dealer_id);
        // $map['dealer_id'] = array('eq',$this->dealer_id);
        $map['status'] = array('eq',0);
        $map['order_id'] = array('eq',$param['order_id']);
        $prefix = C("DB_PREFIX");
        $d = M("dealer_auctioned")->where($map)->find();
        //个人车源 车主争议 车主不卖了
        $map1 = array();
        $map1['order_id'] = array('eq',$param['order_id']);
        $issue = M('owner_issue')->where($map1)->find();
        if ($d) {
            $is_get_status = "待确认";
            if ($param['car_source']==2) {//个人
                if ($param['status'] < 8) {
                    $is_get_status = "待确认";
                }elseif($param['status'] >7 && $param['status']!=12){
                    $is_get_status = "您已竞得";
                }elseif ($param['status']==12) {
                    if (in_array($param['fail_type'], array(1,2,3,7)) ) {
                        $is_get_status = "您未竞得";
                    }elseif ($param['fail_type'] ==4 || $param['fail_type']==7) {
                        $is_get_status = "您已竞得";
                    }elseif ($issue['status'] == 2) {
                        $is_get_status = "您未竞得";
                    }
                }
                
            }elseif ($param['car_source']==1) {//4s
                if ($param['return_check_status'] > 0) {
                    $is_get_status = "您已竞得";
                }elseif ($param['status'] == 12) {
                    if (in_array($param['fail_type'], array(1,2,7)) ) {
                        $is_get_status = "您未竞得";
                    }elseif ($param['fail_type']==4 || $param['fail_type']==7) {
                        $is_get_status = "您已竞得";
                    }
                }
            }
        }else{
            $is_get_status = "您未竞得";
        }
        
        return $is_get_status;
    }

    
    //获取仲裁车列表
    /**
     * @param $page 当前页码
     * @param $limit 页码限制
     * @param $dealer_id 车商ID
     * @param $type 仲裁类型 1待仲裁 2已仲裁
     * @return array
     */
    public function get_arbitrate_list($page, $limit, $dealer_id,$type){
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $map = [];
        $map['da.dealer_id'] = array('eq',$dealer_id);

        switch($type){
            case '1'://待仲裁
                $map['di.status'] = array('eq',0);
                break;
            case '2'://已仲裁
                $map['di.status'] = array('in',array(1,2,3));
                break;
            default:
                $map['di.status'] = array('eq',0);
                break;
        }

        $cols = "o.order_id,o.order_no,o.bidding_end_time,c.composite_state,c.accident_level,di.issue_id,
            c.car_id,c.series_id,c.plate_prefix,c.plate_suffix,c.car_cc,c.turbo,c.gearbox,c.location_area,c.transfer_limit
            ";
        $prefix = C("DB_PREFIX");

        $total = M('dealer_issue')->alias("di")
            ->join($prefix."order as o ON o.order_id=di.order_id")
            ->join($prefix."cars as c ON c.car_id=o.car_id")
            ->join($prefix."dealer_auctioned as da ON da.order_id=o.order_id")
            ->where($map)->count();

        $ret =M('dealer_issue')->alias("di")->field($cols)
            ->join($prefix."order as o ON o.order_id=di.order_id")
            ->join($prefix."cars as c ON c.car_id=o.car_id")
            ->join($prefix."dealer_auctioned as da ON da.order_id=o.order_id")
            ->order("di.createtime desc")
            ->where($map)->page($page)->limit($limit)->select();
        //echo M()->getLastSql();
        $list = array();
        if(!empty($ret)){
            $cm = new CarModel();
            $addr = new Address();
            foreach ($ret as $key => $val) {
                //车型
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $city_name = $addr->get_name_by_code($val['location_area']);
                $list[$key]['car_name'] = '['.$city_name.'] '.$series['name'] . ' ' . $val['car_cc'] . ($val['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $val['gearbox']);

                $list[$key]['order_id'] = $val['issue_id'];

                $img = Car::get_pic_by_key($val['car_id'], "p_left_front45");//左前45°图片
                $list[$key]['img'] = $img['pic_url'];

                $transfer_limit = C('TRANSFER_LIMIT.' . $val['transfer_limit']);
                $list[$key]['desc'] = $val['order_no'].'/'.$transfer_limit.'/上门自提' ;
                $list[$key]['trade_time'] = date('Y-m-d H:i',strtotime($val['bidding_end_time']));

                
            }

        }

        $data = ['total'=>$total,'list'=>$list];
        return $data;
    }

    /*
     * 获取我的代金卷列表
     * */
    public function get_coupon_list()
    {
        $map = array();
        $map['dc.dealer_id'] = array('eq', $this->dealer_id);
        $map['dc.use_status'] = array('eq', '0');
        $map['dc.start_date'] = array('elt', date('Y-m-d'));
        $map['dc.end_date'] = array('egt', date('Y-m-d'));
        $prefix = C("DB_PREFIX");
        $res = M("dealer_coupon")->alias("dc")->field("dc.*,o.order_no,ct.type_name,a.type")
                ->join(" left join ".$prefix."coupon_type as ct on dc.coupon_type_id = ct.coupon_type_id")
                ->join(" left join ".$prefix."activity as a on a.aid = ct.a_id")
                ->join(" left join ".$prefix."lottery_coupon as lc on lc.coupon_id = dc.coupon_id")
                ->join(" left join ".$prefix."scratch_card as sc on sc.cid = lc.card_id")
                ->join(" left join ".$prefix."order as o on o.order_id = sc.order_id")
                ->where($map)->order("end_date")->select();
        return $res;
    }

    public function count()
    {
        $Model = new \Think\Model();
        $sql = $this->count_sql;
        $sql .= " {$this->condition}";
        $sql .= ";";
        $r = $Model->query($sql);
        return $r[0]['count'];
    }


    /**
     * 获取待验车车辆总数
     * @param $dealer_id 车商ID
     * @return int
     */
    public function waitCheckCount($dealer_id){
        $prefix = C("DB_PREFIX");

        $map = array();
        $map['ada.dealer_id'] = array('eq', $dealer_id);
        $map['cdc.status'] = array('eq', 0);

        $total = M('car_dealer_check')->alias("cdc")
            ->join($prefix."order as o ON o.order_id=cdc.order_id")
            ->join($prefix."cars as c ON c.car_id=o.car_id")
            ->join($prefix."dealer_auctioned as ada ON ada.order_id=o.order_id")
            ->where($map)->count();

       return $total;
    }

    /**
    * 活动拍单对应按钮
    **/
    public function get_raffle_botton($order_id){
        $order = new AuOrder($order_id);
        $order_info = $order->detail();
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $botton_info = array();
        $prefix = C("DB_PREFIX");
        if ($order_info['status'] == 11 || $order_info['status'] == 13) {
            //活动类型为2，即抽代金券
            $type = 2;
            //找到对应活动类型的奖券
            $map = array();
            $map['c.order_id'] = $order_id;
            $map['a.type'] = $type;
            $card_info = M('scratch_card')->alias('c')->field('c.*,a.coupon_end_date')
                ->join('left join '. $prefix."activity a  ON c.a_id = a.aid")
                ->where($map)->find();
            $now = date("Y-m-d");
            if ($card_info && $card_info['state'] == 0 && $now <= $card_info['coupon_end_date']) {
                $botton_info[] = array(
                    "name"=>"成交抽奖",
                    "type"=>"1",
                    "url"=>APP_URL."/Raffle/raffle/type/2/order_id/".$order_id,
                    "title"=>"抽奖"
                );
            }
        }
        $redis = new PhpRedis();
        $arr = ['order_id'=>$order_id];
        $redis_key = getRedisKeyByCode('REDIS_KEY','100019',$arr);
        $step = $redis->get($redis_key);
        if (
            (($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 &&  in_array($order_info['return_check_status'], array(5,6,7)) && $car_info['car_source'] ==1 ) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $car_info['car_source'] ==2 )) && !$step && ($order_info['is_lock'] != 1)
            ) {
            $botton_info[] = array(
                "name"=>"车辆结算",
                "type"=>"10"
            );
        }
        $dealer = new Dealer($this->dealer_id);
        $dealer_credit_info = $dealer ->get_dealer_credit();
        if ($order_info['dealer_pay_status'] == 0 && $dealer_credit_info['is_credit'] == 1 && $step) {
            $botton_info[] = array(
                "name"=>"立即支付",
                "type"=>"20"
            );
        }
        return $botton_info;
    }
    //查询拍单当前状态是否发起过争议
    public function get_dispute_status($order_id,$order_status){
        $map['order_id'] = array('eq',$order_id);
        $map['order_sattus'] = array('eq',$order_status);
        $info = M('dispute')->where($map)->find();
        if($info){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 获取拍单最终价格用来结算时插入order_fee
     **/
    public function set_final_price($car_id,$order_id,$type = 1){
        $cols = "o.trade_time,o.scene_id,
            o.order_id,o.order_no,o.status,o.car_id,o.coupon,o.dealer_confirm_status,o.dealer_pay_status,o.bid_best_price,
            o.bidding_best_price,o.commision,o.transfer_fee,o.deliver_type,o.pay_type,o.bidding_end_time,o.compensation,o.first_pay_status,
            c.car_source,crl.status return_status,o.return_check_status,o.check_car_status,o.transfer_type,o.consult_increase,
            c.car_id,c.car_no,c.mbrand_id,brand_id,series_id,model_id,c.car_color,c.plate_suffix,c.plate_prefix,c.car_cc,
            c.turbo,c.gearbox,c.transfer_limit,c.location_area,c.first_reg_date,c.pointer_mileage,c.emission";
        $prefix = C("DB_PREFIX");
        if($car_id){  //判断car_id是否存在
            $map['c.car_id'] = ['eq',$car_id];
        }
        $map['o.order_id'] = ['eq',$order_id];
        $info = M('order')->alias("o")->field($cols)
            ->join("{$prefix}cars as c  ON o.car_id=c.car_id")
            ->join("LEFT JOIN {$prefix}car_return_log as crl  ON crl.order_id=o.order_id")
            ->join("LEFT JOIN {$prefix}proceeds_log as pl ON pl.order_id=o.order_id")
            ->where($map)->find();
        $list = array();
        //拍卖最高价
        $list['success_price'] = $info['bidding_best_price'] > $info['bid_best_price'] ? $info['bidding_best_price'] : $info['bid_best_price'];
        $list['commision'] = $info['commision']; //交易服务费
        $list['transfer_fee'] = $info['transfer_fee']; //交付服务费
        if ($info['transfer_type'] == 1) {
            $list['transfer_fee'] = 0; //车商自过 没有过户费
        }
        $Raffle = new Raffle();
        $Raffle_info = $Raffle->find_card_activity($info['order_id'],1);
        $list['lottery'] = !empty($Raffle_info)?intval($Raffle_info['price']):0;
        $Raffle_money = $Raffle_info['state']>0 ? $list['lottery']:0;
        $list['lottery'] = $Raffle_money; //抽奖立减
        $redis = new PhpRedis();
        $arr = ['order_id'=>$order_id];
        $redis_key_coupon = getRedisKeyByCode('REDIS_KEY','100000',$arr);
        $coupon_ids = $redis->get($redis_key_coupon);
        if($coupon_ids){
            $coupon_id = explode(',',$coupon_ids);
            $use_coupon = $this->get_coupon_price($coupon_id);
            $use_coupon  > $info['coupon'] ? $list['coupon'] = $info['coupon'] : $list['coupon'] = $use_coupon; //代金券金额
        }else{
            $list['coupon'] = 0;
        }
        //场次活动
        $res_activity = $this->is_scene_activity($info['scene_id']);
        if(!empty($res_activity)){
            //根据场次活动减免规则id找到减免规则
            foreach($res_activity as $k => $v){
                if($v['rules_type'] == 2){ //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                    $list['activity_reduction'] = $this->get_activity_rules_price($v['scene_activity_id'],$list['success_price']);
                }else if($v['rules_type'] == 1){ //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                    $list['activity_reduction'] = $v['amount'];
                }
            }
        }else{
            $list['activity_reduction'] = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
        }
        $list['final_price'] = $list['success_price'] + $list['commision'] + $list['transfer_fee'] - $list['coupon'] - $list['lottery'] - $list['activity_reduction'] ;
        $list['order_id'] = $order_id;
        $list['createtime'] = date('Y-m-d H:i:s');
        if($type == 1){
            $order_fee_info = $this->get_order_fee($order_id);
            if($order_fee_info){
                $data['coupon'] = $list['coupon'];
                $data['lottery'] = $list['lottery'];
                if($list['transfer_fee'] == 0){
                    $data['transfer_fee'] = 0;
                }
                $data['createtime'] = date('Y-m-d H:i:s');
                $data['final_price'] = $list['final_price'];
                $res = M('order_fee')->where("order_id = '".$order_id ."'")->save($data);
                return $res;
            }else{
                $res = M('order_fee')->add($list);
                return $res;
            }
        }else{
            return $list['final_price'];
        }

    }
    //计算代金券面额
    public function get_coupon_price($coupon_id){
        $map['coupon_id'] = array('in',$coupon_id);
        $res = M('dealer_coupon')->where($map)->select();
        $total = 0;
        foreach($res as $k => $v){
            $total += $v['amount'];
        }
        return $total;
    }
    //添加order_collections
    public function set_order_collections($data){
        $res = M('order_collections')->add($data);
        return $res;
    }
    //查询改场次是否有活动
    public function is_scene_activity($scene_id){
        $map['sar.scene_id'] = array('eq',$scene_id);
        $map['sa.status'] = array('eq',1); //活动必须为正常状态
        $info = M('scene_activity_relation')->where($map)->alias("sar")->field('sar.id,sar.scene_id,sar.scene_activity_id,sa.name,sa.type,sa.branch_id,sa.rules_type,sa.amount,sa.status')
            ->join(C("DB_PREFIX")."scene_activity as sa ON sa.id = sar.scene_activity_id")
            ->select();
        return $info;
    }
    public function get_activity_rules_price($scene_activity_id,$success_price){
        $map['scene_activity_id'] = array('eq',$scene_activity_id);
        $map['min_bid_price'] = array('elt',$success_price);
        $map['max_bid_price'] = array('egt',$success_price);
        $info = M('activity_rules')->where($map)->find();
        return $info['amount'];
    }
    public function get_order_fee($order_id){
        return M("order_fee")->where("order_id = '". $order_id ."'")->find();
    }
    //将过户方式修改为自过
    public function set_transfer_type($order_id,$transfer_type){
        $map['order_id'] = array('eq',$order_id);
        $data['transfer_type'] = $transfer_type;
        return M('order')->where($map)->save($data);
    }
}

?>
